package com.dongdongshop.freemarkerservice.impl;
import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.freemarkerservice.FreemarkerService;
import com.dongdongshop.pojo.TbGoods;
import com.dongdongshop.pojo.TbGoodsDesc;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.service.TbGoodDescService;
import com.dongdongshop.service.TbGoodsService;
import com.dongdongshop.service.TbItemService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class FreemarkerServiceImpl implements FreemarkerService {
    @Reference
    private TbGoodsService tbGoodsService;
    @Reference
    private  TbGoodDescService tbGoodDescService;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Reference
    private TbItemService tbItemService ;
    @Override
    public void createPage(String[] str) {
        for (int i = 0; i < str.length; i++) {
            createPage2(Long.parseLong(str[i]));
        }
    }
    public void createPage2(Long goodsId) {
        //第一步
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        FileWriter writer = null;
        try {
            //    第四步：加载一个模板，创建一个模板对象。
            Template template = configuration.getTemplate("item.ftl");
            //    第五步：创建一个模板使用的数据集，可以是 pojo 也可以是 map。一般是 Map。
            Map map = new HashMap();
            //第六步：创建一个 Writer 对象，一般创建一 FileWriter 对象，指定生成的文件名。
             writer = new FileWriter("D:\\freemarker\\"+goodsId +".html");
             //商品信息填充
             TbGoods tbGoods =  tbGoodsService.selectByGoodsId(goodsId);
             //根据goodsId查询商品的详情信息
             TbGoodsDesc tbGoodsDesc =  tbGoodDescService.selectDescByGoodsId(goodsId);
             //根据goodsId查询item数据
             List<TbItem> tbItemList = tbItemService.selectByGoodsId(goodsId);
             map.put("tbGoods",tbGoods);
             map.put("tbGoodsDesc",tbGoodsDesc);
             map.put("itemList",tbItemList);
            //第七步：调用模板对象的 process 方法输出文件
            template.process(map,writer);
            //    第八步：关闭流
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(writer!=null){
                writer.close();}
            } catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
